package com.example.sunmiv1.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.StockInquiryAdapter;
import com.example.sunmiv1.entity.StockInquiryGoodBean;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.activity.CaptureActivity;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


//  庫存查詢
public class StockInquiryActivity extends Activity {


    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.inventorySearch_edit)
    EditText inventorySearchEdit;
    @BindView(R.id.inventorySearch_search)
    ImageView inventorySearchSearch;
    @BindView(R.id.inventorySearch_code)
    ImageView inventorySearchCode;
    @BindView(R.id.inventorySearch_list)
    PullToRefreshListView inventorySearchList;
    @BindView(R.id.inventorySearch_popup_freightNumber)
    TextView inventorySearchPopupFreightNumber;
    @BindView(R.id.inventorySearch_popup_inventory)
    EditText inventorySearchPopupInventory;
    @BindView(R.id.inventorySearch_popup_stock)
    TextView inventorySearchPopupStock;
    @BindView(R.id.inventorySearch_popup_cancel)
    TextView inventorySearchPopupCancel;
    @BindView(R.id.inventorySearch_popup_sure)
    TextView inventorySearchPopupSure;
    @BindView(R.id.inventorySearch_popup_linear)
    LinearLayout inventorySearchPopupLinear;
    @BindView(R.id.inventorySearch_popup_name)
    TextView inventorySearchPopupName;

    private Context context;
    private ACache aCache;
    private LoadingDialog loadingDialog;
    private StockInquiryGoodBean stockInquiryGoodBean;
    private List<StockInquiryGoodBean.ListBean> list;
    private StockInquiryAdapter stockInquiryAdapter;

    private int index = 0;

    private int page = 1; //第幾頁
    private int page_limit = 10; //一頁有多少數據

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    loadingDialog.dismiss();
                    inventorySearchList.onRefreshComplete();
                    int size = stockInquiryGoodBean.getList().size();
                    Toast.makeText(context, stockInquiryGoodBean.getMsg(), Toast.LENGTH_SHORT).show();
                    if (size > 0) {
                        if (page==1)
                        list.clear();
                        for (int i = 0; i < size; i++) {
                            list.add(stockInquiryGoodBean.getList().get(i));
                        }
                    }
                    setInventorySearchAdapter();
                    break;
                case 2:
                    loadingDialog.dismiss();
                    inventorySearchList.onRefreshComplete();
                    if (page != 1) {
                        Toast.makeText(context, "沒有更多數據了", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, stockInquiryGoodBean.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                    setInventorySearchAdapter();
                    break;
            }
        }
    };

    private String search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_stock_inquiry);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        ButterKnife.bind(this);
        search = getIntent().getStringExtra("search");
        if (search != null) {
            titleTitle.setText(R.string.stockInquiryTip1);
        } else {
            titleTitle.setText(R.string.stockInquiryTip2);
        }
        list = new ArrayList<>();
        if (search == null) {
            inventorySearchList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    index = position;
                    inventorySearchPopupName.setText(context.getResources().getString(R.string.collectingSilver_goodName) + list.get(position).getGoods_name());
                    inventorySearchPopupFreightNumber.setText(context.getResources().getString(R.string.inventory_freightNumber) + list.get(position).getGoods_number());
//                    inventorySearchPopupInventory.setText(list.get(position).getCheck_num());
                    inventorySearchPopupStock.setText(context.getResources().getString(R.string.inventory_stock) + list.get(position).getGoods_num());
                    inventorySearchPopupLinear.setVisibility(View.VISIBLE);
                }
            });
        }
        inventorySearchList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                list.clear();
                setInventorySearchAdapter();
                searchGood(inventorySearchEdit.getText().toString());
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                searchGood(inventorySearchEdit.getText().toString());
            }
        });
//        searchGood("");
    }

    private void setInventorySearchAdapter() {
        if (stockInquiryAdapter == null) {
            stockInquiryAdapter = new StockInquiryAdapter(context, list);
            inventorySearchList.setAdapter(stockInquiryAdapter);
        } else {
            stockInquiryAdapter.notifyDataSetChanged();
        }
    }

    @OnClick({R.id.title_back, R.id.inventorySearch_search, R.id.inventorySearch_code,
            R.id.inventorySearch_popup_cancel, R.id.inventorySearch_popup_sure, R.id.inventorySearch_popup_linear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.inventorySearch_search:
                if ("".equals(inventorySearchEdit.getText().toString())) {
                    Toast.makeText(context, "請輸入搜索關鍵字", Toast.LENGTH_SHORT).show();
                    return;
                }
                page = 1;
                list.clear();
                setInventorySearchAdapter();
                searchGood(inventorySearchEdit.getText().toString());
                break;
            case R.id.inventorySearch_code:
                startQrCode();
                break;
            case R.id.inventorySearch_popup_cancel:
                inventorySearchPopupLinear.setVisibility(View.GONE);
                break;
            case R.id.inventorySearch_popup_sure:
                submit();
                break;
            case R.id.inventorySearch_popup_linear:
                break;
        }
    }

    // 開始掃碼
    private void startQrCode() {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 二維碼掃碼
        Intent intent = new Intent(context, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    Toast.makeText(context, "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != 1 && requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {//掃描結果回調
            Bundle bundle = data.getExtras();
            page = 1;
            list.clear();
            setInventorySearchAdapter();
            searchGood(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
        }
    }

    private void searchGood(String keyword) {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("keyword", keyword);
            jsonObject.put("page", page);
            jsonObject.put("limit", page_limit);
            HttpUtils.post(context, Common.SEARCH_GOOD_NEW, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    stockInquiryGoodBean = GsonUtils.JsonToBean(text, StockInquiryGoodBean.class);
                    Message msg = new Message();
                    if (stockInquiryGoodBean.getStatus() == 1) {
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void submit() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("pd_num", inventorySearchPopupInventory.getText().toString());
//            jsonObject.put("id", list.get(index).getId());
            HttpUtils.post(context, Common.SUBMIT_INVENTORY, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        loadingDialog.dismiss();
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            inventorySearchPopupLinear.setVisibility(View.GONE);
                            list.clear();
                            searchGood(inventorySearchEdit.getText().toString());
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
